/** *
 *  @param {number} sizeInBytes
 *  @returns {string}
 *  字节=>字符串格式['Bytes', 'KB', 'MB', 'GB', 'TB']
 **/
export const formatFileSize = (sizeInBytes) => {
  const units = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  let size = sizeInBytes
  let unitIndex = 0
  while (size >= 1024 && unitIndex < units.length - 1) {
    size >>= 10
    unitIndex++
  }
  return size.toFixed(2) + ' ' + units[unitIndex]
}

const unitToBytes = {
  B: 1,
  KB: 1024,
  MB: 1024 * 1024,
  GB: 1024 * 1024 * 1024,
  TB: 1024 * 1024 * 1024 * 1024
}
/** *
 *  @param {string} sizeString
 *  @returns {number}
 *  ['B', 'KB', 'MB', 'GB', 'TB']字符串格式=>字节
 **/
const parseSizeStringToBytes = (sizeString) => {
  const sizePattern = /^(\d+)([KMGTP]?B?)$/i
  const matches = sizeString.match(sizePattern)

  if (!matches) {
    throw new Error('无效的大小字符串')
  }
  const value = parseFloat(matches[1])
  const unit = matches[2].toUpperCase()
  if (!unitToBytes[unit]) {
    throw new Error('无效的大小单位')
  }
  return value * unitToBytes[unit]
}

/** *
 *  @param {File} file
 *  @param {string} maxSizeString
 *  @returns {boolean}
 *  当前文件{file}大小是否大于指定大小{maxSizeString}
 **/
export const fileSizeExceeds = (file, maxSizeString) => {
  const maxSizeInBytes = parseSizeStringToBytes(maxSizeString)
  return file.size > maxSizeInBytes
}

/** *
 *  @param {1 | 2 | 3 | 4 | 5} level
 *  @returns {number}
 *  根据level决定返回的时间格式：
 *  level = 1 时，只输出年份；
 *  level = 2 时，输出年份和月份；
 *  level = 3 时，输出年份、月份和日期；
 *  level = 4 时，输出年份、月份、日期和时间（时、分）；
 *  level = 5 时，输出 ISO 时间格式（年-月-日T时:分:秒）；
 **/
export const formatDate = (level = 2) => {
  const now = new Date()
  let date
  switch (level) {
    case 1:
      date = now.getFullYear()
      break
    case 2:
      date =
        now.getFullYear() +
        '' +
        (now.getMonth() + 1).toString().padStart(2, '0')
      break
    case 3:
      date =
        now.getFullYear() +
        '' +
        (now.getMonth() + 1).toString().padStart(2, '0') +
        '' +
        now.getDate().toString().padStart(2, '0')
      break
    case 4:
      date =
        now.getFullYear() +
        '' +
        (now.getMonth() + 1).toString().padStart(2, '0') +
        '' +
        now.getDate().toString().padStart(2, '0') +
        '' +
        now.getHours().toString().padStart(2, '0') +
        '' +
        now.getMinutes().toString().padStart(2, '0')
      break
    default:
      date = now.toLocaleString()
  }
  return date
}
